from test_demo.data_processing import get_data
from tool_class.db_connection import get_connection
from .config_data.case_data import *
import pytest
from tool_class.page_handle import DataTreatingPageHandle

@pytest.fixture(scope='module')
def channel_allocation_module(session_page):
    handle = DataTreatingPageHandle(session_page)
    #进入基础配置-渠道配置
    handle.goto_local(local_path="baseSettings-1007", url_path="/ins/#/settings/baseSettings")
    yield session_page, handle

@pytest.fixture(scope='function')
def channel_allocation_function(channel_allocation_module):
    session_page, handle = channel_allocation_module
    yield session_page, handle
    session_page.mouse.move(0, 0) #测试结束后需要退出二级页
    session_page.mouse.click(x=0, y=0)


@pytest.mark.run(order=950)
def test_channel_allocation_add_01(channel_allocation_function):
    """ 验证渠道新增 """
    session_page, handle = channel_allocation_function
    result = handle.add_handle(channel_add_001)
    print("操作数据---", result)
    channel_list = result['数据集列表']
    handle.element_click("baseSetting-channel-r-10001")
    handle.element_click("baseSetting-channel-form-10003") #点击查看渠道分类列表
    assert result['名称'] in channel_list \
           and session_page.get_by_role("menuitem",name=result['名称']).is_visible()

@pytest.mark.run(order=951)
def test_channel_allocation_add_02(channel_allocation_function):
    """ 验证渠道编辑 """
    session_page, handle = channel_allocation_function
    element_index = handle.get_element_index("baseSetting-channel-left-10002",channel_add_001['input.名称']["value"])
    handle.element_click(f"baseSetting-channel-left-10002-{element_index}") #选中渠道
    handle.element_click(f"baseSetting-channel-left-10003-{element_index}") #点击编辑渠道分类
    result = handle.add_handle(channel_edit_001)
    print("操作数据---", result)
    channel_list = result['数据集列表']
    handle.element_click("baseSetting-channel-r-10001")
    handle.element_click("baseSetting-channel-form-10003") #点击查看渠道分类列表
    assert result['名称'] in channel_list \
           and session_page.get_by_role("menuitem",name=result['名称']).is_visible()


@pytest.mark.parametrize("unit",[class_add_001,class_edit_002,class_edit_003,class_edit_001])
@pytest.mark.run(order=952)
def test_class_allocation_add_01(channel_allocation_function,unit):
    """ 验证分类新增编辑 """
    session_page, handle = channel_allocation_function
    result = handle.add_handle(unit)
    keys = list(result.keys())
    verify_key = keys[1]
    print("操作数据---", result)
    assert result[verify_key] in result['数据集列表'][0]

@pytest.mark.run(order=953)
def test_class_allocation_del_01(channel_allocation_function):
    """ 删除当前有渠道的分类 """
    session_page, handle = channel_allocation_function
    element_index = handle.get_element_index("baseSetting-channel-left-10002",channel_edit_001['input.名称']["value"])
    handle.element_click(f"baseSetting-channel-left-10004-{element_index}") #点击删除渠道分类
    assert session_page.get_by_role("alert").inner_text() == "该渠道分类或其子分类下存在渠道信息，请先删除渠道信息"
    sql = f"""delete from ins_channel where name = '{class_edit_001['input.名称']['value']}' limit 1"""
    print(f"sql语句---{sql}")
    conn = get_connection("富通东方", "mysql_query")
    try:
        with conn.cursor() as cursor:  # cursor 对象允许你执行SQL语句并获取结果  ，使用with后自动关闭游标
            # 使用cursor.execute()执行一个语句
            cursor.execute(sql)
            conn.commit()
    except Exception as e:
        # 如果出现错误，回滚事务
        conn.rollback()
        print(f"An error occurred: {e}")
    finally:
        # 关闭连接
        conn.close()

@pytest.mark.parametrize("unit",[required_fields_001,required_fields_002])
@pytest.mark.run(order=954)
def test_channel_allocation_add_03(channel_allocation_function,unit):
    """ 验证必填项 """
    session_page, handle = channel_allocation_function
    result = handle.add_handle(unit)
    expect_value = next(iter(result))
    assert session_page.get_by_role("alert").inner_text() == expect_value

@pytest.mark.parametrize("unit",[length_01,length_02,length_03,length_04])
@pytest.mark.run(order=955)
def test_channel_allocation_add_04(channel_allocation_function,unit):
    """ 验证字段长度 """
    session_page, handle = channel_allocation_function
    result = handle.add_handle(unit)
    keys = list(result.keys())
    first_key = keys[-1]  # 获取最后一个字段名称
    expected_length = first_key.split('_')[-1]
    assert len(result[first_key]) == int(expected_length)

@pytest.mark.run(order=956)
def test_channel_allocation_add_05(channel_allocation_module):
    """ 新增二级分类 """
    session_page, handle = channel_allocation_module
    result = handle.add_handle(channel_add_002)
    handle.goto_local("processing-1002","/ins/#/dataCenter/processing") #去数据处理查看是否新增成功
    handle.pull_cascade("processing-custom-1004",[f"{channel_edit_001['input.名称']['value']}>click"])
    assert session_page.get_by_role("menuitem",name=result['名称']).is_visible()
    handle.goto_local(local_path="baseSettings-1007", url_path="/ins/#/settings/baseSettings")

@pytest.mark.parametrize("unit",["编辑","新增","删除"])
@pytest.mark.run(order=957)
def test_channel_allocation_add_06(channel_allocation_function,unit):
    """ 验证当前分类中所属分类没有当前分类 """
    session_page, handle = channel_allocation_function
    element_index = handle.get_element_index("baseSetting-channel-left-10002",channel_edit_001['input.名称']["value"])
    handle.element_click(f"baseSetting-channel-left-10002-{element_index}") #选中渠道分类
    if unit == "编辑":
        handle.element_click(f"baseSetting-channel-left-10003-{element_index}") #点击编辑渠道分类
        handle.element_click("baseSetting-channel-form-10003") #点击所属分类
        assert not session_page.get_by_role("menuitem",name=channel_edit_001['input.名称']["value"]).is_visible() \
                and not session_page.get_by_role("menuitem",name="默认分类").is_visible()
    elif unit == "新增":
        handle.button_click("baseSetting-channel-left-10001") #点击新增分类
        channel_name = handle.get_values({"当前分类": "baseSetting-channel-form-10003"})
        handle.element_click("baseSetting-channel-form-10003")  # 点击所属分类
        assert session_page.get_by_role("menuitem", name=channel_edit_001['input.名称']["value"]).is_visible() \
                and channel_name['当前分类'] == channel_edit_001['input.名称']["value"] \
                and not session_page.get_by_role("menuitem", name="默认分类").is_visible()
    else:
        handle.element_click(f"baseSetting-channel-left-10004-{element_index}")  # 删除渠道分类
        channel_list = handle.get_list_data("baseSetting-channel-left-10002")
        assert channel_edit_001['input.名称']["value"] not in channel_list \
               and not session_page.get_by_role("menuitem", name="默认分类").is_visible()

@pytest.mark.run(order=958)
def test_class_allocation_del_02(channel_allocation_module):
    """ 删除分类后去查看下拉框是否消失 """
    session_page, handle = channel_allocation_module
    handle.goto_local("processing-1002","/ins/#/dataCenter/processing")
    handle.element_click("processing-custom-1004")
    assert not session_page.get_by_role("menuitem",name=channel_edit_001['input.名称']['value']).is_visible()